# -*- coding: utf-8 -*-
'''
@文件    :sms.py
@说明    :短信服务(short message service)
@时间    :2024/12/12 14:18:31
@作者    :浪晋
@版本    :1.0
'''
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


class AliyunSMS:
    def __init__(self,SecretId: str, SecretKey: str, SmsSdkAppId: str, SignName: str):
        self.SecretId = SecretId
        self.SecretKey = SecretKey
        self.SmsSdkAppId = SmsSdkAppId  # 阿里云不需要此参数
        self.SignName = SignName
                
    def get_client(self) -> Dysmsapi20170525Client:
        """
        使用凭据初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            access_key_id=self.SecretId,
            access_key_secret=self.SecretKey
        )
        # Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = f'dysmsapi.aliyuncs.com'
        client = Dysmsapi20170525Client(config)
        return client
    
    def send_sms(
            self, 
            TemplateCode: str,
            phone: str,
            param: str
        ):
        """
        发送短信
        响应格式:{"SendStatusSet": [{"SerialNo": "3363:140938803417349340998207606", "PhoneNumber": "+8618202876063", "Fee": 1, "SessionContext": "", "Code": "Ok", "Message": "send success", "IsoCode": "CN"}], "RequestId": "c51c04ac-8af2-44aa-8d28-72309aa7e6af"}
        """
        client = self.get_client()
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            phone_numbers=phone,
            sign_name=self.SignName,
            template_code=TemplateCode,
            template_param=param
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            response = client.send_sms_with_options(send_sms_request, runtime)
            return response.body
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)

